package com.xuzz.study.datastructure;

import java.util.concurrent.atomic.AtomicInteger;

public class LinkedBlockingQueue<E> implements BlockingQueue<E> {

    private final AtomicInteger count = new AtomicInteger(0);

    private  int capacity;

    /**
     * 头结点
     */
    transient Node<E> head;

    /**
     * 尾节点
     */
    private transient Node<E> tail;

    public LinkedBlockingQueue(int capacity)
    {
        this.capacity = capacity;

        this.tail = this.head = new Node<>(null);
    }

    @Override
    public boolean offer(E item) {
        if(this.capacity == count.get())
        {
            return false;
        }

        Node<E> node = new Node<E>(item);

        tail = tail.next = node;
        count.getAndIncrement();
        return true;
    }

    @Override
    public E take() {
        Node<E> node = head.next;
        if(null==node)
        {
            return null;
        }
        E item = node.item;
        head = node;
        return item;
    }

    static class Node<E>{
        E item;
        Node<E> next;

        Node(E item)
        {
            item = item;
        }
    }
}
